package com.itheima.publisher.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqConfig implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //从容器中获取RabbitTemplate,设置return方法
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                String exchange = returnedMessage.getExchange();
                String message = new String(returnedMessage.getMessage().getBody());
                String routingKey = returnedMessage.getRoutingKey();
                log.warn("消息发送失败，exchange: {}, routingKey: {}, message: {}", exchange, routingKey, message);
                // 可以在这里添加其他处理逻辑，比如记录到数据库或发送告警等
            }
        });
    }
}